package cn.xuexiluxian.open.framework.security.configuration;

import cn.xuexiluxian.open.common.constant.Constants;
import cn.xuexiluxian.open.framework.security.filter.MobileCaptchaAuthenticationFilter;
import cn.xuexiluxian.open.framework.security.filter.MobileCaptchaCodeValidateFilter;
import cn.xuexiluxian.open.framework.security.handler.CustomAuthenticationFailureHandler;
import cn.xuexiluxian.open.framework.security.handler.CustomAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

@Component
public class MobileAuthenticationConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    @Autowired
    CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
    @Autowired
    CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
    @Autowired
    UserDetailsService mobileUserDetailsService;
    /**
     * 手机验证码过滤器
     */
    @Autowired
    private MobileCaptchaCodeValidateFilter mobileKaptchaCodeValidateFilter;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 创建校验手机号过滤器实例
        MobileCaptchaAuthenticationFilter mobileAuthenticationFilter = new MobileCaptchaAuthenticationFilter();
        mobileAuthenticationFilter.setFilterProcessesUrl(Constants.MOBILE_LOGIN_URL);
        // 接收 AuthenticationManager 认证管理器
        mobileAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        // 采用哪个成功、失败处理器
        mobileAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
        mobileAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);
        // 为 Provider 指定明确 的mobileUserDetailsService 来查询用户信息
        MobileAuthenticationProvider provider = new MobileAuthenticationProvider();
        provider.setUserDetailsService(mobileUserDetailsService);
        // 将 provider 绑定到 HttpSecurity 上面，
        // 并且将手机认证加到用户名密码认证之后
        http.authenticationProvider(provider)
                .addFilterBefore(mobileKaptchaCodeValidateFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterAfter(mobileAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
